<template>
  <div class="content">
    <div class="content-head">
      <el-form :inline="true" :model="formData" label-position="left">
        <el-form-item label="班组" label-width="70px" class="form-item">
          <el-select v-model="formData.classTeam" size="mini" clearable placeholder="请选择班组">
            <el-option v-for="item,index in formData.classTeamList" :label="item" :value="item" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报工日期" label-width="70px" class="form-item">
          <el-date-picker v-model="formData.reportDate" type="date" size="mini" value-format="yyyy-MM-dd" :editable="false" clearable placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="车间" label-width="70px" class="form-item">
          <el-select v-model="formData.workshop" size="mini" clearable placeholder="选择车间">
            <el-option label="装配线" value="装配线"></el-option>
            <el-option label="机加工" value="机加工"></el-option>
            <el-option label="走心机" value="走心机"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工序" label-width="70px" class="form-item">
          <el-select v-model="formData.processName" size="mini" clearable placeholder="请选择工序">
            <el-option label="热处理" value="热处理"></el-option>
            <el-option label="车床" value="车床"></el-option>
            <el-option label="铣床" value="铣床"></el-option>
            <el-option label="清洗机" value="清洗机"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button type="primary" size="mini" icon="el-icon-refresh-left" @click="reset_btn">重置</el-button>
        <el-button type="success" size="mini" icon="el-icon-search" @click="search_btn">查询</el-button>
        <el-button type="info" size="mini" icon="el-icon-download" @click="export_btn">导出</el-button>
        <el-button v-if="teamInfo === 1 || teamInfo === 2" :disabled="tableSelectedRow.length === 0" type="danger" size="mini" icon="el-icon-notebook-1" @click="batchCheck_btn">批量审核</el-button>
      </div>
    </div>
    <div class="content-table">
      <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" height="100%" :tree-props="{children: 'materialRecordList', hasChildren: 'hasChildren'}" @selection-change="handleSelectionChange" class="content-table-item">
          <el-table-column v-if="teamInfo === 1 || teamInfo === 2" type="selection" :selectable="selectable" width="55"></el-table-column>
          <el-table-column prop="reportDate" label="报工日期" width="100"></el-table-column>
          <el-table-column prop="workShop" label="车间" width=""></el-table-column>
          <el-table-column prop="workReportType" label="工序/线体" width="100"></el-table-column>
          <el-table-column prop="teamName" label="班组" width=""></el-table-column>
          <el-table-column prop="productNumber" label="订单编号" width="150"></el-table-column>
          <el-table-column prop="productName" label="品名" width="120"></el-table-column>
          <el-table-column prop="productCode" label="品号" width="100"></el-table-column>
          <el-table-column prop="machine" label="生产设备" width="150"></el-table-column>
          <el-table-column prop="operator" label="作业员"></el-table-column>
          <el-table-column prop="completedQuantity" label="完成数量"></el-table-column>
          <el-table-column prop="qualifiedQuantity" label="合格数量"></el-table-column>
          <el-table-column prop="unqualifiedQuantity" label="不良数量"></el-table-column>
          <el-table-column prop="classes" label="班次"></el-table-column>
          <el-table-column prop="createdDate" label="创建时间" width="160"></el-table-column>
          <el-table-column prop="" label="操作" width="200"  fixed="right">
            <template slot-scope="{ row, $index }">
              <template v-if="teamInfo === 1 || teamInfo === 2">
                <el-button type="text" :disabled="row.reviewStatus === 2" @click="edit_btn(row)">编辑</el-button>
                <el-button type="text" :disabled="row.reviewStatus !== 0 || row.appealStatus === 1" @click="check_btn(row)">审核</el-button>
                <el-button type="text" :disabled="row.reviewStatus !== 2" @click="examine_btn(row)">查看</el-button>
                <el-button type="text" v-if="row.appealStatus === 1" @click="viewAppeal_btn(row)">查看申诉</el-button>
              </template>
              <template v-if="teamInfo === 0">
                <el-button type="text" :disabled="row.appealStatus === 1 || row.reviewStatus === 2" @click="appeal_btn(row)">{{ row.appealStatus === 0 ? '申 诉' : '申诉中' }}</el-button>
                <el-button type="text" @click="examine_btn(row)">查 看</el-button>
              </template>
            </template>
          </el-table-column>
      </el-table>
    </div>
    <div class="content-footer">
      <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50,100]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
    </div>
    <!-- dialog -->
    <div v-if="dialogVisible">
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="80%" @close="dialogCancel_btn" class="dialog-content">
        <workorder1 v-if="tempData.workShopCode == 0" :tempData="tempData" :state="dialogState" ref="workorder" @message="getMessage"></workorder1>
        <workorder2 v-if="tempData.workShopCode == 1 || tempData.workShopCode == 2" :tempData="tempData" :state="dialogState" ref="workorder" @message="getMessage"></workorder2>
        <span slot="footer" class="dialog-footer">
          <template v-if="dialogState === 0">
            <template v-if="tempData.reviewStatus == 0">
              <el-button size="small" @click="dialogCheckCancel_btn">取 消</el-button>
              <el-button type="primary" size="small" @click="dialogCheckConfirm_btn">通过审核</el-button>
            </template>
            <el-button v-else type="primary" size="small" @click="dialogCheckCancel_btn">取消</el-button>
          </template>
          <template v-if="dialogState === 1">
            <el-button size="small" @click="dialogCancel_btn">取 消</el-button>
            <el-button type="primary" size="small" @click="dialogConfirm_btn">确 定</el-button>
          </template>
        </span>
      </el-dialog>
    </div>
    <!-- 申诉内容dialog -->
    <el-dialog :title="complainDialogState === 0 ? '编辑申诉' : '查看申诉'" :visible.sync="complainDialog" width="40%" :before-close="complainCancel">
      <el-input type="textarea" :rows="3" placeholder="请输入申诉内容" v-model="complainTextarea"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="complainCancel" >取 消</el-button>
        <el-button size="small" type="primary" v-if="complainDialogState === 0" @click="complainConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqWorkOrderList, reqClassesList, reqExportReportsWorkOrder, reqCheckPass, reqCheckPassBatch, reqCheckIsTeam, reqSaveData, reqClassTeamList } from "@/api/workOrder.js";
import workorder1 from "@/components/workOrder/workOrder1.vue";
import workorder2 from "@/components/workOrder/workOrder2.vue";
import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
export default {
  components:{
    workorder1,
    workorder2
  },
  data() {
    return {
      formData:{
        classTeam:"",
        reportDate:"",
        workshop:"",  //车间
        processName:"",
        classTeamList:[]
      },
      tableData:[],
      currentPage:1,
      pageSize:10,
      total:0,
      dialogVisible:false,  //dialog弹出层
      dialogState:0,  //dialog弹出层状态 0-审核 1-编辑 2-查看
      tempData:null,  //中转变量
      complainTextarea:"",  //申诉文本域
      complainDialog:false,
      complainDialogState:0,  //申诉dialog的状态
      teamInfo:null,  //用户信息 2-管理员 1-班组组长 0-班组成员
      tableLoading:false,
      tableSelectedRow:[]
    }
  },
  computed:{
    dialogTitle(){
      let state = this.dialogState;
      if(state === 0){
        return "审核";
      }
      if(state === 1){
        return "编辑";
      }
      if(state === 2){
        return "查看"
      }
    },
  },
  mounted(){
    setTimeout(() => {
      this.checkTeamInfo();
      this.getWorkOrderList();
      this.getClassTeamList();
    },300)
    //精致环境下进行自动旋转
    autoOrientation();
  },
  methods:{
    //分页获取报工列表信息
    async getWorkOrderList () {
      this.tableLoading = true;
      const { classTeam, reportDate, workshop, processName } = this.formData;
      const parameters = {page:this.currentPage, size:this.pageSize, teamName:classTeam, reportDate:reportDate, workShop:workshop, workReportType:processName};
      reqWorkOrderList(parameters).then(res => {
        if(res.data.code === 200){
          this.tableData = res.data.data.content;
          this.total = res.data.data.totalElements;
        }
        this.tableLoading = false;
        console.log("分页获取工单列表信息",res);
      }).catch(err => {
        this.$message({type:"error",message:"列表数据获取失败"});
        this.tableLoading = false;
      })
    },
    //获取班次信息
    async getClassesList () {
      reqClassesList().then(res => {
        if(res.data.code === 200){
            //this.formData.classesList = res.data.data;
        }
        console.log('获取班次信息api',res);
      }).catch(err => {
        this.$message({type:"error",message:"班次信息获取失败"});
      })
    },
    //查询重置导出按钮
    search_btn(){
      this.currentPage = 1;
      this.pageSize = 10;
      const { classTeam, reportDate, workshop, processName } = this.formData;
      if(classTeam === "" && reportDate === "" && workshop === "" && processName === ""){
        this.$message({type:"warning",message:"搜索条件为空!"});
        return;
      }
      const parameters = {
        page:this.currentPage,
        size:this.pageSize,
        teamName:classTeam,
        reportDate:reportDate,
        workShop:workshop,
        workReportType:processName
      }
      this.tableLoading = true;
      reqWorkOrderList(parameters).then(res => {
        if(res.data.code === 200){
          this.tableLoading = false;
          this.tableData = res.data.data.content;
          this.total = res.data.data.totalElements;
        }
        console.log("分页获取工单列表信息",res);
      }).catch(err => {
        this.tableLoading = false;
        this.$message({type:"error",message:"查询失败，请重试"});
      })
    },
    reset_btn(){
      this.formData.classTeam = "";
      this.formData.reportDate = "";
      this.formData.workshop = "";
      this.formData.processName = "";
      this.currentPage = 1;
      this.pageSize = 10;
      //重新获取表格数据
      this.getWorkOrderList();
    },
    export_btn() {
      this.$confirm('即将导出当前内容', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
          .then(async () => {
              this.exportBtnLoading = true;
              let res = await reqExportReportsWorkOrder();
              if (res.status === 200) {
                  let blob = res.data;
                  let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
                  const aLink = document.createElement('a');
                  aLink.href = url;
                  let timestamp = new Date().getTime();
                  aLink.setAttribute('download', '工单报工信息列表_' + timestamp);
                  document.body.appendChild(aLink);
                  aLink.click();
                  document.body.removeChild(aLink);
                  this.$message.success('导出成功');
                  this.exportBtnLoading = false;
              } else {
                  this.$message.error('导出失败,请重试');
                  this.exportBtnLoading = false;
              }
          }).catch(() => {
              this.$message({type: 'info', message: '已取消导出!'});          
          });
    },
    //分页器
    handleCurrentChange(curPage){
      this.currentPage = curPage;
      //重新获取数据
      this.getWorkOrderList();
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize;
      //重新获取数据
      this.getWorkOrderList();
    },
    //表格的审核 查看 编辑按钮
    check_btn(row){
      this.dialogState = 0;
      this.dialogVisible = true;
      //赋值
      this.tempData = row;
    },
    examine_btn(row){
      this.dialogState = 2;
      this.dialogVisible = true;
      //赋值
      this.tempData = row;
    },
    edit_btn(row){
      this.dialogVisible = true;
      this.dialogState = 1;
      //赋值
      this.tempData = row;
    },
    viewAppeal_btn(row){
      this.complainDialog = true;
      this.complainTextarea = row.appealRemark;
      this.complainDialogState = 1;
    },
    appeal_btn(row){
      this.complainDialog = true;
      //赋值
      this.tempData = row;
      this.complainDialogState = 0;
    },
    //dialog相关按钮-编辑状态下
    dialogCancel_btn(){
      this.dialogVisible = false;
      this.dialogState = 0;
      //清空tempData
      this.tempData = null;
    },
    dialogConfirm_btn(){
      //编辑状态
      this.$refs.workorder.save_btn();
    },
    //dialog相关按钮-审核状态下
    dialogCheckCancel_btn(){
      this.dialogCancel_btn();
    },
    dialogCheckConfirm_btn(){
      //通过审核
      let parameter = this.tempData;
      reqCheckPass(parameter).then(res => {
        if(res.status === 200){
          this.$message({type:"success",message:"已提交审核通过!"});
          //关闭
          this.dialogCancel_btn();
          this.getWorkOrderList();
        }
        console.log("审核通过api",res);
      }).catch(err => {
        this.$message({type:"error",message:"审核失败，请重试!"});
      })
    },
    //申诉dialog的取消、确定按钮
    complainCancel(){
      this.complainDialog = false;
      this.complainTextarea = "";
      this.complainDialogState = 0;
    },
    complainConfirm(){
      //申诉
      let content = this.complainTextarea;
      if(content.trim() === "") return this.$message({type:"info",message:"请输入申诉内容!"});
      this.tempData.appealRemark = content;
      this.tempData.appealStatus = 1;
      reqSaveData(this.tempData).then(res => {
        if(res.data.code === 200){
          //成功
          this.$message({type:"success",message:"申诉成功!"});
          //关闭
          this.complainCancel();
          //重新请求列表数据
          this.getWorkOrderList();
        } else {
          this.$message({type:"error",message:"申诉失败,请重试!"});
        }
        console.log('保存或更新工单api',res);
      }).catch(err => {
        this.$message({type:"info",message:err});
      })
    },
    //编辑状态下子组件保存成功否的通知
    getMessage(flag){
      console.log(flag);
      if(flag){
        //编辑成功
        this.$message({type:"success",message:"编辑修改成功!"});
        //关闭dialog
        this.dialogCancel_btn();
        //重新获取报工列表信息
        this.getWorkOrderList();
      } else {
        //编辑失败
        this.$message({type:"success",message:"编辑修改失败!"});
      }
    },
    //判断用户类别 2-管理员 1-班组长 0-组员
    checkTeamInfo() {
      reqCheckIsTeam().then(res => {
        if(res.data.code === 200){
          this.teamInfo = res.data.data;
        }
        console.log('判断当前用户类别',res);
      }).catch(err => {
        this.$message({type:"error",message:"班组信息获取失败"});
      })
    },
    //获取班组列表信息
    getClassTeamList() {
      reqClassTeamList().then(res => {
        if(res.data.code === 200){
          this.formData.classTeamList = res.data.data.map(item => item.teamName);
        }
      }).catch(error => {
        this.$message({type:"error",message:"获取班组列表信息出错"});
      })
    },
    batchCheck_btn(){
      this.$confirm('此操作将批量审核所选工单, 是否继续?', '提示', {closeOnClickModal:false,confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {
        const ids = this.tableSelectedRow;
        const tmp = [];
        for(let i = 0; i < ids.length; i ++){
          tmp.push({id:ids[i]});
        }
        reqCheckPassBatch(tmp).then(response => {
          if(response.data.code === 200){
            this.$message({type:"success",message:"审核成功"});
            //更新页面数据
            this.getWorkOrderList();
          }
          console.log('批量审核api',response);
        }).catch(error => {
          this.$message({type:"error",message:"批量审核失败，请重试"});
        })
      }).catch(() => {});
    },
    handleSelectionChange(selectedColumn){
      let tmp = [];
      for(let i = 0; i < selectedColumn.length; i ++){
        tmp.push(selectedColumn[i].id);
      }
      this.tableSelectedRow = tmp;
      console.log("选择的行",selectedColumn);
    },
    selectable(row, index) {
      return row.reviewStatus == 0;
    },
    //格式化时间
    formatDate(val,type){
        let date = new Date(val);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        if(type === 0){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 1){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day);
        } else if (type === 2){
            return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 3){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
        }
    },
    addZero(val){
        return val > 9 ? val : "0" + val;
    }
  }
}
</script>

<style lang='scss' scoped>
.content{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 2% 5%;
  box-sizing: border-box;

  .content-head{
    flex: 1;
    .form-item{
      margin-right: 2vw;
    }
  }
  .content-table{
    flex: 5;
    margin: 10px 0;
  }
  .content-footer{
    flex: 0.5;
    display: flex;
    justify-content: flex-end;
  }
}
</style>